package cn.kgc.javaweb.servlet;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author: mosin
 * @version: v1.0  2022/3/22
 * 文件下载
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        String fileName = req.getParameter("fileName");
        File file = new File("D:\\upload", fileName);
        FileInputStream fis = new FileInputStream(file);
        //设置响应的数据为文件
        resp.setContentType("application/octet-stream;charset=utf-8");
        // 浏览器接受到响应后  如果浏览器能解析当前文件 则浏览器直接打开    设置响应的格式为附件    解决文件下载的中文乱码
        resp.setHeader("Content-Disposition", "attachment; filename="+new String(fileName.getBytes("gb2312"), "ISO8859-1" ));

        //通过响应对象获取输出流
        ServletOutputStream outputStream = resp.getOutputStream();
        //实现流的对拷  完成文件的下载
        IOUtils.copy(fis,outputStream);
        System.out.println("文件下载完毕!");

    }
}
